#ifndef DIELECTRIC_H
#define DIELECTRIC_H
#include<material.h>
#include<utils.h>
class dielectric:public material
{
public:
    dielectric(float ri):ref_idx(ri){}
    virtual bool scatter(const ray&r_in,const hit_record &rec,QVector3D&attenuation,ray&scattered)const
    {
        QVector3D outward_normal;
        QVector3D reflected=reflect(r_in.direction(),rec.normal);
        float ni_over_nt;
        attenuation=QVector3D(1.0,1.0,1.0);
        QVector3D refracted;
        float reflect_prob;
        float cosine;
        if(QVector3D::dotProduct(r_in.direction(),rec.normal)>0)
        {
            outward_normal=-rec.normal;
            ni_over_nt=ref_idx;
            cosine=ref_idx*QVector3D::dotProduct(r_in.direction(),rec.normal)/r_in.direction().length();
        }
        else {

            outward_normal=rec.normal;
            ni_over_nt=1.0/ref_idx;
            cosine=-QVector3D::dotProduct(r_in.direction(),rec.normal)/r_in.direction().length();
        }
        if(refract(r_in.direction(),outward_normal,ni_over_nt,refracted))
        {
//            scattered=ray(rec.p,refracted);
            reflect_prob=schlick(cosine,ref_idx);
        }
        else
        {
            scattered=ray(rec.p,reflected,r_in.time());
            reflect_prob=1.0;
//            return false;
        }
        if(Random::get(0.0,0.99)<reflect_prob)
        {
            scattered=ray(rec.p,reflected,r_in.time());
        }else {
            scattered=ray(rec.p,refracted,r_in.time());
        }
        return true;
    }
    float ref_idx;//相对折射率 n2/n1
};

#endif // DIELECTRIC_H
